package com.google.code.jproxybridge;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.StringTokenizer;

public final class HttpRequest {

    private String method;

    private String url;

    private String httpVersion;

    private final byte[] request;

    private final Map<String, String> attributes;

    public HttpRequest(byte[] data) {
        String strData = new String(data);
        int headerEndPos = strData.indexOf("\r\n\r\n");
        strData = strData.substring(0, headerEndPos);
        headerEndPos += 4;
        request = new byte[data.length - headerEndPos];
        System.arraycopy(data, headerEndPos, request, 0, request.length);
        int destinationEndPos = strData.indexOf("\r\n");
        StringTokenizer tz = new StringTokenizer(strData.substring(0, destinationEndPos), " ");

        method = tz.nextToken();
        url = tz.nextToken();
        httpVersion = tz.nextToken();

        strData = strData.substring(destinationEndPos + 2);
        tz = new StringTokenizer(strData, "\r\n");

        attributes = new LinkedHashMap<String, String>();
        while (tz.hasMoreTokens()) {
            String line = tz.nextToken();
            int pos = line.indexOf(':');
            String key = line.substring(0, pos);
            String value = line.substring(pos + 2);
            attributes.put(key, value);
        }
    }

    public byte[] getData() {
        StringBuilder sb = new StringBuilder(method);
        sb.append(' ').append(url).append(' ').append(httpVersion).append("\r\n");

        for (Entry<String, String> e : attributes.entrySet()) {
            sb.append(e.getKey()).append(": ").append(e.getValue()).append("\r\n");
        }
        sb.append("\r\n");

        byte[] header = sb.toString().getBytes();
        byte[] ret = new byte[header.length + request.length];
        System.arraycopy(header, 0, ret, 0, header.length);
        System.arraycopy(request, 0, ret, header.length, request.length);
        return ret;
    }

    public String getMethod() {
        return method;
    }

    public void setMethod(String method) {
        this.method = method;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getHttpVersion() {
        return httpVersion;
    }

    public void setHttpVersion(String httpVersion) {
        this.httpVersion = httpVersion;
    }

    public String getAttribute(String name) {
        return attributes.get(name);
    }

    public String setAttribute(String name, String value) {
        return attributes.put(name, value);
    }

    public String removeAttribute(String name) {
        return attributes.remove(name);
    }

}
